<?php

namespace App\Http\Controllers;

use App\Models\ForeignSpeakerCollection;
use App\Models\Speaker;
use App\Models\InvitationApply;
use App\Models\UserCollection;
use App\Models\Project;
use App\Models\ProjectMeetingInvitationSpeaker;
use App\Models\SmsLog;
use App\Models\User;
use App\Models\UsersAuthen;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class UserCenterController extends BaseController
{

    /**
     * 个人中心-邀约申请列表
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-09-26
     * @param Request $request
     * @return void
     */
    public function invitationList(Request $request)
    {
        $rules = [
            'page' => ['required'],
            'limit' => ['required'],
        ];

        $message = [
            'page.required' => '页码不能为空',
            'limit.required' => '限制条数不能为空',
        ];

        $payload = $request->only('page', 'limit', 'speaker_name', 'datetime');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }


        $list = InvitationApply::getInvitationApplyList($payload);

        return successPaginate($list ?? []);
    }


    /**
     * 撤销原因
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-10-29
     * @param Request $request
     * @return void
     */
    public function invitationRevoke(Request $request)
    {
        $rules = [
            'revoke_remark' => ['required'],
            'id' => ['required'],
        ];

        $message = [
            'revoke_remark.required' => '请输入撤销原因',
            'id.required' => '缺少参数',
        ];

        $payload = $request->only('id', 'revoke_remark');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }


        $list = InvitationApply::setRevokeRemarks($payload);

        return success();
    }


    /**
     * 我的关注列表
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2022-03-04
     * @param Request $request
     * @return json
     */
    public function followList(Request $request)
    {
        $rules = [
            // 'type' => ['required'],
            'page' => ['required'],
            'limit' => ['required'],
        ];

        $message = [
            // 'type.required' => '请输入分类',
            'page.required' => '请输入页码',
            'limit.required' => '请输入限制条数',

        ];

        $payload = $request->only('name', 'page', 'limit');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }

        $userId =  userId();
        $where = ['user_id' => $userId, 'type' => 8, 'status' => 1];

        $id_arr = UserCollection::where($where)->pluck('info_id')->toArray();

        $model = new Speaker();
        $list = $model->getForeignSpeakerList((int) $payload['page'], (int) $payload['limit'], $id_arr, $payload['name']);
        $list = infoArray($list, $id_arr, []);

        // 获取用户参与的项目
        $project_ids = Project::where(['user_id' => $userId, 'project_status' => 2])->pluck('id');
        // 根据已完成项目查找合作过的讲者ProjectMeetingInvitationSpeaker
        $partner_ids = ProjectMeetingInvitationSpeaker::whereIn('project_id', $project_ids)
            ->where('invitation_status', 1)
            ->pluck('speaker_id');
        if (!empty($partner_ids)) {
            $partner_ids = $partner_ids->toArray();
        }
        $list = partner($list, $partner_ids);
        return successPaginate($list);
    }


    /**
     * 个人中心-个人信息修改
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-09-27
     * @param Request $request
     * @return void
     */
    public function userCenterInfoUpdate(Request $request)
    {
        $rules = [
            'company_name' => ['required'],
        ];

        $message = [
            'company_name.required' => '请输入机构名称',
        ];

        $payload = $request->only('avatar', 'company_name', 'realname', 'email');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }
        $userId =  userId();

        $user = User::find($userId);
        $user->avatar = isset($payload['avatar']) && !empty($payload['avatar']) ? $payload['avatar'] : null;
        $user->company_name = isset($payload['company_name']) && !empty($payload['company_name']) ? $payload['company_name'] : null;
        $user->realname = isset($payload['realname']) && !empty($payload['realname']) ? $payload['realname'] : null;
        $user->email = isset($payload['email']) && !empty($payload['email']) ? $payload['email'] : null;
        if ($user->save()) {
            return success();
        } else {
            return fail_message();
        }
    }


    /**
     * 个人中心 - 认证信息
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-09-27
     * @param Request $request
     * @return void
     */
    public function userCenterAuthUpdate(Request $request)
    {
        $rules = [
            'real_name' => ['required'],
            'unit' => ['required'],
            'department' => ['required'],
            'title' => ['required'],
            'level' => ['required'],
            'id_card_number' => ['required'],
            'certificate' => ['required'],

            'province_id' => ['required'],
            'city_id' => ['required'],
            'district_id' => ['required'],
        ];

        $message = [
            'real_name.required' => '请输入真实姓名',
            'unit.required' => '请输入医院名称',
            'department.required' => '请输入科室',
            'title.required' => '请输入职称',
            'level.required' => '请输入医院级别',
            'id_card_number.required' => '请输入身份证号码',
            'certificate.required' => '请输上传医师资格证/工作证',

            'province_id.required' => '请选择省份',
            'city_id.required' => '请选择城市',
            'district_id.required' => '请选择区域',
        ];

        $payload = $request->only('real_name', 'unit', 'department', 'title', 'email', 'level', 'id_card_number', 'certificate', 'province_id', 'city_id', 'district_id');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }
        $userId =  userId();

        DB::beginTransaction();
        try {
            infoLog(json_encode($payload));
            $user = UsersAuthen::updateOrCreate(
                ['user_id' => $userId],
                [
                    'real_name' => $payload['real_name'],
                    'unit' => $payload['unit'],
                    'department' => $payload['department'],
                    'title' => $payload['title'],
                    'level' => $payload['level'],
                    'id_card_number' => $payload['id_card_number'],
                    'certificate' => $payload['certificate'],

                    'province_id' => $payload['province_id'],
                    'city_id' => $payload['city_id'],
                    'district_id' => $payload['district_id'],
                    'status' => 0,
                    'reason' => null,
                    'examine_time' => null,
                ]
            );

            if ($user) {
                User::where('id', $userId)->update([
                    'realname' => $payload['real_name']
                ]);
                DB::commit();
                return success();
            } else {
                return fail_message();
            }
        } catch (Exception $e) {
            DB::rollBack();
            return fail_message($e->getMessage());
        }
    }


    /**
     * 更换手机号
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-09-27
     * @param Request $request
     * @return void
     */
    public function changePhone(Request $request)
    {
        $rules = [
            'code' => ['required'],
            'phone' => ['required'],
        ];

        $message = [
            'code.required' => '请输入验证码',
            'phone.required' => '请输入手机号码',
        ];

        $payload = $request->only('code', 'phone');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }
        // 验证验证码
        $verify_code = SmsLog::check_code($payload['code'], $payload['phone']);

        if (empty($verify_code)) {
            return fail_message('验证码不正确');
        }

        $userId =  userId();

        DB::beginTransaction();
        try {

            $users = User::where('username', $payload['phone'])->first();
            if ($users) {
                return fail([], '手机号码已存在', 500);
            }
            User::where('id', $userId)->update([
                'phone' => $payload['phone'],
                'username' => $payload['phone']
            ]);
            UsersAuthen::updateOrCreate(
                ['user_id' => $userId],
                [
                    'phone' => $payload['phone'],
                ]
            );
            DB::commit();
            return success();
        } catch (Exception $e) {
            DB::rollBack();
            Log::error('修改手机号码失败了' . $e->getMessage());
            return fail($e, '修改失败了', 500);
        }
    }

    /**
     * 重置密码
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-09-27
     * @param Request $request
     * @return void
     */
    public function resetPassword(Request $request)
    {
        $rules = [
            'old_password' => ['required'],
            'new_password' => ['required'],
            'confirm_password' => ['required'],
        ];

        $message = [
            'old_password.required' => '请输入旧密码',
            'new_password.required' => '请输入新密码',
            'confirm_password.required' => '请输入确认密码',
        ];

        $payload = $request->only('old_password', 'new_password', 'confirm_password');

        $validator = Validator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }
        $user = user();
        if (!password_verify($payload['old_password'], $user->password)) {
            return fail_message('旧密码不正确');
        }

        $user->password = bcrypt($payload['confirm_password']);
        $user->save();
        return success();
    }

    /**
     * 生成ppt
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-09-30
     * @param Request $request
     * @return void
     */
    public function ppt(Request $request)
    {
        $rules = [
            'collection_id' => ['required'],
        ];

        $message = [
            'collection_id.required' => '请选择集合',
        ];

        $payload = $request->only('collection_id');

        $validator = Validator::make($payload, $rules, $message);

        if (is_numeric($payload['collection_id'])) {
            $surveyId = $payload['collection_id'];
        } else {
            $surveyId = stringToId($payload['collection_id']);
        }

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }
        // ForeignSpeakerCollection
        $model = new ForeignSpeakerCollection();
        $data = $model->createPpt((int) $surveyId);
        // dd($data);
        return success($data);
    }
}
